package com.ssy.lingxi.member.merchant.serviceimpl.web;

import com.ssy.lingxi.common.constant.basic.EnableDisableStatus;
import com.ssy.lingxi.common.constant.basic.UserLoginSourceEnum;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.member.merchant.entity.*;
import com.ssy.lingxi.member.merchant.model.bo.AuthBO;
import com.ssy.lingxi.member.merchant.model.bo.ButtonBO;
import com.ssy.lingxi.member.merchant.model.constant.MemberUserAuthTypeEnum;
import com.ssy.lingxi.member.merchant.model.vo.basic.request.AuthTreeGetButtonVO;
import com.ssy.lingxi.member.merchant.model.vo.basic.response.AuthTreeButtonVO;
import com.ssy.lingxi.member.merchant.model.vo.basic.response.AuthTreeMenuButtonCheckIdVO;
import com.ssy.lingxi.member.merchant.model.vo.basic.response.AuthTreeMenuVO;
import com.ssy.lingxi.member.merchant.model.vo.maintenance.request.*;
import com.ssy.lingxi.member.merchant.model.vo.maintenance.response.*;
import com.ssy.lingxi.member.merchant.repository.*;
import com.ssy.lingxi.member.merchant.service.base.IBaseAuthService;
import com.ssy.lingxi.member.merchant.service.base.IBaseMemberCacheService;
import com.ssy.lingxi.member.merchant.service.feign.IWorkflowFeignService;
import com.ssy.lingxi.member.merchant.service.web.IMemberAbilityRoleService;
import com.ssy.lingxi.member.merchant.utils.AuthBOUtils;
import com.ssy.lingxi.member.merchant.utils.MemberOrganizationUtil;
import com.ssy.lingxi.member.merchant.utils.NumberUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 会员自定义角色服务接口实现类
 *
 * @author 万宁
 * @version 2.0.0
 * @date 2020-06-30
 */
@Service
public class MemberAbilityRoleServiceImpl implements IMemberAbilityRoleService {
    @Resource
    private MemberRepository memberRepository;

    @Resource
    private MemberOrganizationRepository memberOrganizationRepository;

    @Resource
    private MemberRoleRepository memberRoleRepository;

    @Resource
    private MemberRoleAuthConfigRepository memberRoleAuthConfigRepository;

    @Resource
    private MenuRepository menuRepository;

    @Resource
    private IBaseMemberCacheService memberCacheService;

    @Resource
    private IBaseAuthService baseAuthService;

    @Resource
    private IWorkflowFeignService workflowFeignService;

    /**
     * 分页、模糊查询会员角色
     *
     * @param headers HttpHeaders信息
     * @param pageVO  接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<PageData<MemberRoleQueryVO>> pageMemberRole(HttpHeaders headers, MemberRolePageVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        MemberDO memberDO = memberRepository.findById(loginUser.getMemberId()).orElse(null);
        if (memberDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_DOES_NOT_EXIST);
        }

        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), Sort.by("id").ascending());
        Specification<MemberRoleDO> specification = (Specification<MemberRoleDO>) (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();

            Join<Object, Object> memberJoin = root.join("member", JoinType.LEFT);
            list.add(criteriaBuilder.equal(memberJoin.get("id").as(Long.class), loginUser.getMemberId()));

            if (pageVO.getStatus() != null) {
                list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), pageVO.getStatus()));
            }

            if (StringUtils.hasLength(pageVO.getRoleName())) {
                list.add(criteriaBuilder.like(root.get("roleName").as(String.class), "%" + pageVO.getRoleName().trim() + "%"));
            }

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        Page<MemberRoleDO> result = memberRoleRepository.findAll(specification, page);

        return Wrapper.success(new PageData<>(result.getTotalElements(), result.getContent().stream().map(r -> {
            MemberRoleQueryVO queryVO = new MemberRoleQueryVO();
            queryVO.setId(r.getId());
            queryVO.setRoleName(r.getRoleName());
            queryVO.setRemark(r.getRemark());
            queryVO.setStatus(r.getStatus());
            queryVO.setImFlag(r.getHasImAuth());
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * 根据名称，分页、模糊查询会员角色
     *
     * @param headers HttpHeaders信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MemberRoleQueryVO>> pageMemberRoleByName(HttpHeaders headers, MemberRolePageByNameVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        MemberDO memberDO = memberRepository.findById(loginUser.getMemberId()).orElse(null);
        if (memberDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_DOES_NOT_EXIST);
        }

        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), Sort.by("id").ascending());
        Specification<MemberRoleDO> specification = (Specification<MemberRoleDO>) (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();

            Join<Object, Object> memberJoin = root.join("member", JoinType.LEFT);
            list.add(criteriaBuilder.equal(memberJoin.get("id").as(Long.class), loginUser.getMemberId()));

            list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), EnableDisableStatus.ENABLE.getCode()));

            if (StringUtils.hasLength(pageVO.getRoleName())) {
                list.add(criteriaBuilder.like(root.get("roleName").as(String.class), "%" + pageVO.getRoleName().trim() + "%"));
            }

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        Page<MemberRoleDO> result = memberRoleRepository.findAll(specification, page);

        return Wrapper.success(new PageData<>(result.getTotalElements(), result.getContent().stream().map(r -> {
            MemberRoleQueryVO queryVO = new MemberRoleQueryVO();
            queryVO.setId(r.getId());
            queryVO.setRoleName(r.getRoleName());
            queryVO.setRemark(r.getRemark());
            queryVO.setStatus(r.getStatus());
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * 获取左侧权限菜单、组织机构
     *
     * @param headers HttpHeaders信息
     * @return 操作结果
     */
    @Override
    public Wrapper<MemberAbilityRoleAuthConfigVO> treeMemberAuth(HttpHeaders headers, MemberRoleIdVO idVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        MemberDO memberDO = memberRepository.findById(loginUser.getMemberId()).orElse(null);
        if (memberDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_DOES_NOT_EXIST);
        }

        MemberAuthDO memberAuth = memberDO.getMemberAuth();
        if(memberAuth == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_AUTH_DOES_NOT_EXIST);
        }

        List<AuthBO> roleAuthList = new ArrayList<>();
        List<MemberRoleAuthConfigDO> authConfigList = new ArrayList<>();
        if(NumberUtil.isPositive(idVO.getMemberRoleId())) {
            MemberRoleDO memberRoleDO = memberRoleRepository.findById(idVO.getMemberRoleId()).orElse(null);
            if(memberRoleDO == null || !memberRoleDO.getMember().getId().equals(loginUser.getMemberId())) {
                return Wrapper.fail(ResponseCode.MC_MS_MEMBER_ROLE_DOES_NOT_EXIST);
            }

            roleAuthList = memberRoleDO.getAuth();
            authConfigList = new ArrayList<>(memberRoleDO.getAuthConfig());
        }

        MemberAbilityRoleAuthConfigVO configVO = new MemberAbilityRoleAuthConfigVO();
        configVO.setOrgs(MemberOrganizationUtil.transferToTree(new ArrayList<>(memberDO.getOrgs())));

        configVO.setMenus(transferToTree(memberAuth.getAuth(), roleAuthList, authConfigList));

        return Wrapper.success(configVO);
    }

    /**
     * 构建权限菜单树结构
     * @param memberAuthList 会员权限列表
     * @param roleAuthList   角色权限列表
     * @param authConfigList  角色数据权限
     * @return 树形菜单
     */
    private List<MemberAbilityAuthTreeMenuVO> transferToTree(List<AuthBO> memberAuthList, List<AuthBO> roleAuthList, List<MemberRoleAuthConfigDO> authConfigList) {
        if(CollectionUtils.isEmpty(memberAuthList)) {
            return new ArrayList<>();
        }

        List<MemberAbilityAuthTreeMenuVO> resultList = new ArrayList<>();

        //找到第一级菜单
        List<AuthBO> topList = memberAuthList.stream().filter(t -> t.getParentId().equals(0L)).sorted(Comparator.comparingInt(AuthBO::getOrder)).collect(Collectors.toList());
        //循环、递归构建树
        topList.forEach(top -> {
            MemberAbilityAuthTreeMenuVO topVO = new MemberAbilityAuthTreeMenuVO();
            topVO.setId(top.getId());
            topVO.setTitle(top.getTitle());
            topVO.setButtons(top.getButtons().stream().map(button -> new AuthTreeButtonVO(button.getButtonId(), button.getTitle())).collect(Collectors.toList()));
            AuthBO roleAuth = roleAuthList.stream().filter(auth -> auth.getId().equals(top.getId())).findFirst().orElse(null);
            topVO.setButtonIds(Objects.isNull(roleAuth) ? new ArrayList<>() : roleAuth.getButtons().stream().map(ButtonBO::getButtonId).collect(Collectors.toList()));
            MemberRoleAuthConfigDO authConfig =  authConfigList.stream().filter(config -> config.getMenu().getId().equals(top.getId())).findFirst().orElse(null);
            topVO.setHasDataAuth(Objects.isNull(authConfig) ? 0 : 1);
            topVO.setOrgIds(Objects.isNull(authConfig) ? new ArrayList<>() : authConfig.getOrgs().stream().map(MemberOrganizationDO::getId).collect(Collectors.toList()));
            topVO.setChildren(new ArrayList<>());

            recurseTree(topVO, top.getId(), memberAuthList, roleAuthList, authConfigList);
            resultList.add(topVO);
        });

        return resultList;
    }

    /**
     * 递归构建权限树
     * @param topVO 上级菜单VO
     * @param topAuthId   上级权限菜单Id
     * @param memberAuthList 会员权限列表
     * @param roleAuthList   角色权限列表
     * @param authConfigList 角色数据权限配置
     */
    private  void recurseTree(MemberAbilityAuthTreeMenuVO topVO, Long topAuthId , List<AuthBO> memberAuthList, List<AuthBO> roleAuthList, List<MemberRoleAuthConfigDO> authConfigList) {
        List<AuthBO> subList = memberAuthList.stream().filter(s -> s.getParentId().equals(topAuthId)).sorted(Comparator.comparingInt(AuthBO::getOrder)).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(subList)) {
            return;
        }

        for (AuthBO sub : subList) {
            MemberAbilityAuthTreeMenuVO menuBO = new MemberAbilityAuthTreeMenuVO();
            menuBO.setId(sub.getId());
            menuBO.setTitle(sub.getTitle());
            menuBO.setButtons(sub.getButtons().stream().map(button -> new AuthTreeButtonVO(button.getButtonId(), button.getTitle())).collect(Collectors.toList()));
            AuthBO roleAuth = roleAuthList.stream().filter(auth -> auth.getId().equals(sub.getId())).findFirst().orElse(null);
            menuBO.setButtonIds(Objects.isNull(roleAuth) ? new ArrayList<>() : roleAuth.getButtons().stream().map(ButtonBO::getButtonId).collect(Collectors.toList()));
            MemberRoleAuthConfigDO authConfig =  authConfigList.stream().filter(config -> config.getMenu().getId().equals(sub.getId())).findFirst().orElse(null);
            menuBO.setHasDataAuth(Objects.isNull(authConfig) ? 0 : 1);
            menuBO.setOrgIds(Objects.isNull(authConfig) ? new ArrayList<>() : authConfig.getOrgs().stream().map(MemberOrganizationDO::getId).collect(Collectors.toList()));
            menuBO.setChildren(new ArrayList<>());

            topVO.getChildren().add(menuBO);
            recurseTree(menuBO, sub.getId(), memberAuthList, roleAuthList, authConfigList);
        }
    }

    /**
     * 根据左侧菜单Id，查询右侧按钮列表，是否可配置数据权限信息
     *
     * @param headers  HttpHeaders信息
     * @param buttonVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<MemberAbilityRoleAuthButtonVO> getMemberAuthButtons(HttpHeaders headers, AuthTreeGetButtonVO buttonVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        MemberDO memberDO = memberRepository.findById(loginUser.getMemberId()).orElse(null);
        if (memberDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_DOES_NOT_EXIST);
        }

        MemberAuthDO memberAuth = memberDO.getMemberAuth();
        if(memberAuth == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_AUTH_DOES_NOT_EXIST);
        }

        MenuDO menuDO = menuRepository.findById(buttonVO.getMenuId()).orElse(null);
        if (menuDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MENU_DOES_NOT_EXIST);
        }

        MemberAbilityRoleAuthButtonVO authButtonVO = new MemberAbilityRoleAuthButtonVO();

        List<AuthTreeButtonVO> buttonVOList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(memberAuth.getAuth())) {
            AuthBO authBO = memberAuth.getAuth().stream().filter(auth -> auth.getId().equals(buttonVO.getMenuId())).findFirst().orElse(null);
            if (authBO == null) {
                return Wrapper.fail(ResponseCode.MC_MS_MEMBER_AUTH_DOES_NOT_EXIST);
            }

            if (!CollectionUtils.isEmpty(authBO.getButtons())) {
                buttonVOList = authBO.getButtons().stream().map(button -> new AuthTreeButtonVO(button.getButtonId(), button.getTitle())).collect(Collectors.toList());
            }
        }

        authButtonVO.setButtons(buttonVOList);
        authButtonVO.setDataAuthConfig(menuDO.getDataAuthConfig());

        return Wrapper.success(authButtonVO);
    }

    /**
     * 查询右侧勾选的按钮Id列表
     *
     * @param headers  HttpHeaders信息
     * @param buttonVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<MemberAbilityRoleGetAuthVO> getButtonCheckIds(HttpHeaders headers, MemberRoleButtonVO buttonVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        MemberDO memberDO = memberRepository.findById(loginUser.getMemberId()).orElse(null);
        if (memberDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_DOES_NOT_EXIST);
        }

        MemberAuthDO memberAuth = memberDO.getMemberAuth();
        if(memberAuth == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_AUTH_DOES_NOT_EXIST);
        }

        AuthBO authBO = memberAuth.getAuth().stream().filter(auth -> auth.getId().equals(buttonVO.getMenuId())).findFirst().orElse(null);
        if (authBO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_AUTH_DOES_NOT_EXIST);
        }

        MenuDO menuDO = menuRepository.findById(buttonVO.getMenuId()).orElse(null);
        if (menuDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MENU_DOES_NOT_EXIST);
        }

        MemberRoleDO memberRoleDO = memberRoleRepository.findFirstByMemberAndId(memberDO, buttonVO.getMemberRoleId());
        if (memberRoleDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_ROLE_DOES_NOT_EXIST);
        }

        MemberAbilityRoleGetAuthVO result = new MemberAbilityRoleGetAuthVO();

        //查询会员角色的按钮列表，返回checkIds
        List<Long> checkIds = new ArrayList<>();
        if (!CollectionUtils.isEmpty(memberRoleDO.getAuth())) {
            AuthBO roleAuthBO = memberRoleDO.getAuth().stream().filter(a -> a.getId().equals(buttonVO.getMenuId())).findFirst().orElse(null);
            if (roleAuthBO != null) {
                checkIds = roleAuthBO.getButtons().stream().map(ButtonBO::getButtonId).collect(Collectors.toList());
            }
        }

        result.setCheckIds(checkIds);

        //菜单是否可配置数据权限：在MemberAbilityRoleGetAuthVO的构造函数中已经初始化了各个字段，所以这里可以直接返回
        if (menuDO.getDataAuthConfig().equals(EnableDisableStatus.DISABLE.getCode())) {
            return Wrapper.success(result);
        } else {
            result.setDataAuthConfig(EnableDisableStatus.ENABLE.getCode());
        }

        if (CollectionUtils.isEmpty(memberRoleDO.getAuthConfig())) {
            result.setHasDataAuth(EnableDisableStatus.DISABLE.getCode());
        } else {
            MemberRoleAuthConfigDO authConfigDO = memberRoleDO.getAuthConfig().stream().filter(config -> config.getMenu().getId().equals(buttonVO.getMenuId())).findFirst().orElse(null);
            if (authConfigDO == null) {
                result.setHasDataAuth(EnableDisableStatus.DISABLE.getCode());
            } else {
                result.setHasDataAuth(authConfigDO.getHasDataAuth());

                if (!CollectionUtils.isEmpty(authConfigDO.getOrgs())) {
                    result.setOrgIds(authConfigDO.getOrgs().stream().map(MemberOrganizationDO::getId).collect(Collectors.toList()));
                }
            }
        }

        return Wrapper.success(result);
    }

    /**
     * 新增会员角色
     *
     * @param headers HttpHeaders信息
     * @param addVO   接口参数
     * @return 操作结果
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Wrapper<Void> addMemberRole(HttpHeaders headers, MemberAbilityRoleAddVO addVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        MemberDO memberDO = memberRepository.findById(loginUser.getMemberId()).orElse(null);
        if (memberDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_DOES_NOT_EXIST);
        }

        MemberAuthDO memberAuth = memberDO.getMemberAuth();
        if(memberAuth == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_AUTH_DOES_NOT_EXIST);
        }

        if (memberRoleRepository.existsByMemberAndRoleName(memberDO, addVO.getRoleName())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_ROLE_EXISTS);
        }

        List<AuthBO> authBOList = memberAuth.getAuth();
        if (CollectionUtils.isEmpty(authBOList)) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_AUTH_DOES_NOT_EXIST);
        }

        if(CollectionUtils.isEmpty(addVO.getAuth())) {
            addVO.setAuth(new ArrayList<>());
        }

        //角色权限可能为空
        //参数校验：角色菜单权限
        List<Long> configMenuIds = addVO.getAuth().stream().filter(MemberAbilityDataAuthVO::getChecked).map(MemberAbilityDataAuthVO::getMenuId).collect(Collectors.toList());
        List<MenuDO> menuDOList = menuRepository.findByIdInAndSourceNot(configMenuIds, UserLoginSourceEnum.BUSINESS_MANAGEMENT_PLATFORM.getCode()).stream().sorted(Comparator.comparingLong(MenuDO::getId)).collect(Collectors.toList());
        if (configMenuIds.stream().anyMatch(configMenuId -> menuDOList.stream().noneMatch(menuDO -> menuDO.getId().equals(configMenuId)))) {
            return Wrapper.fail(ResponseCode.MC_MS_MENU_DOES_NOT_EXIST);
        }

        List<Long> menuIds = memberAuth.getAuth().stream().map(AuthBO::getId).collect(Collectors.toList());
        if (configMenuIds.stream().anyMatch(configMenuId -> !menuIds.contains(configMenuId))) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_AUTH_DOES_NOT_EXIST);
        }

        List<Long> dataAuthConfigMenuIds = menuDOList.stream().filter(menuDO -> menuDO.getDataAuthConfig() != null && menuDO.getDataAuthConfig().equals(EnableDisableStatus.ENABLE.getCode())).map(MenuDO::getId).collect(Collectors.toList());
        List<Long> configHasDataAuthConfigMenuIds = addVO.getAuth().stream().filter(auth -> auth.getChecked() && NumberUtil.notNullOrZero(auth.getHasDataAuth()) && auth.getHasDataAuth().equals(EnableDisableStatus.ENABLE.getCode())).map(MemberAbilityDataAuthVO::getMenuId).collect(Collectors.toList());
        if(configHasDataAuthConfigMenuIds.stream().anyMatch(configId -> !dataAuthConfigMenuIds.contains(configId))) {
            return Wrapper.fail(ResponseCode.MC_MS_MENU_CAN_NOT_SET_DATA_AUTH);
        }

        //参数校验：关联的组织机构
        List<Long> configOrgIds = addVO.getAuth().stream().filter(auth -> auth.getChecked() && !CollectionUtils.isEmpty(auth.getOrgIds())).flatMap(auth -> auth.getOrgIds().stream()).distinct().collect(Collectors.toList());
        List<Long> memberOrgIds = memberDO.getOrgs().stream().map(MemberOrganizationDO::getId).collect(Collectors.toList());
        if (configOrgIds.stream().anyMatch(configOrgId -> !memberOrgIds.contains(configOrgId))) {
            return Wrapper.fail(ResponseCode.MC_MS_ORGANIZATION_DOES_NOT_EXIST);
        }

        //保存：角色权限菜单
        List<AuthBO> roleAuthList = memberAuth.getAuth().stream().filter(m -> configMenuIds.contains(m.getId())).collect(Collectors.toList());
        roleAuthList.forEach(roleAuth -> addVO.getAuth().stream().filter(auth -> auth.getChecked() && auth.getMenuId().equals(roleAuth.getId())).findFirst().ifPresent(auth -> {
            if(CollectionUtils.isEmpty(auth.getButtonIds())) {
                roleAuth.setButtons(new ArrayList<>());
            } else {
                roleAuth.getButtons().removeIf(button -> !auth.getButtonIds().contains(button.getButtonId()));
            }
        }));

        //保存：数据权限配置
        List<MemberRoleAuthConfigDO> authConfigList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(addVO.getAuth())) {
            authConfigList = addVO.getAuth().stream().filter(auth -> auth.getChecked() && NumberUtil.notNullOrZero(auth.getHasDataAuth()) && auth.getHasDataAuth().equals(EnableDisableStatus.ENABLE.getCode())).map(auth -> {
                MemberRoleAuthConfigDO authConfigDO = new MemberRoleAuthConfigDO();
                authConfigDO.setMemberId(memberDO.getId());
                //关联的菜单
                authConfigDO.setMenu(menuDOList.stream().filter(menu -> menu.getId().equals(auth.getMenuId())).findFirst().orElse(null));

                //是否具有数据权限
                authConfigDO.setHasDataAuth(EnableDisableStatus.ENABLE.getCode());

                //数据权限关联的组织机构
                if(CollectionUtils.isEmpty(auth.getOrgIds())) {
                    authConfigDO.setOrgs(new HashSet<>());
                } else {
                    authConfigDO.setOrgs(memberDO.getOrgs().stream().filter(memberOrganizationDO -> auth.getOrgIds().contains(memberOrganizationDO.getId())).collect(Collectors.toSet()));
                }

                return authConfigDO;
            }).collect(Collectors.toList());

            if(!CollectionUtils.isEmpty(authBOList)) {
                memberRoleAuthConfigRepository.saveAll(authConfigList);
            }
        }

        MemberRoleDO memberRoleDO = new MemberRoleDO();
        memberRoleDO.setMember(memberDO);
        memberRoleDO.setTypeEnum(MemberUserAuthTypeEnum.NORMAL.getCode());
        memberRoleDO.setStatus(EnableDisableStatus.ENABLE.getCode());
        memberRoleDO.setAuth(roleAuthList);
        memberRoleDO.setHasImAuth(addVO.getImFlag() ? EnableDisableStatus.ENABLE.getCode() : EnableDisableStatus.DISABLE.getCode());
        memberRoleDO.setUsers(new HashSet<>());
        memberRoleDO.setRoleName(addVO.getRoleName());
        memberRoleDO.setRemark(StringUtils.hasLength(addVO.getRemark()) ? addVO.getRemark().trim() : "");
        memberRoleDO.setAuthConfig(new HashSet<>(authConfigList));

        memberRoleRepository.saveAndFlush(memberRoleDO);

        //通知工作流服务
        workflowFeignService.upsertMemberRoleToProcessAsync(loginUser.getMemberId(), memberRoleDO.getId(), memberRoleDO.getRoleName(), roleAuthList);
        return Wrapper.success();
    }

    /**
     * 查询单个会员角色的信息
     *
     * @param headers HttpHeaders信息
     * @param idVO    接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<MemberRoleGetVO> getMemberRole(HttpHeaders headers, MemberRoleIdVO idVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        MemberDO memberDO = memberRepository.findById(loginUser.getMemberId()).orElse(null);
        if (memberDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_DOES_NOT_EXIST);
        }

        MemberRoleDO memberRoleDO = memberRoleRepository.findFirstByMemberAndId(memberDO, idVO.getMemberRoleId());
        if (memberRoleDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_ROLE_DOES_NOT_EXIST);
        }

        MemberAuthDO memberAuth = memberDO.getMemberAuth();
        if(memberAuth == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_AUTH_DOES_NOT_EXIST);
        }

        MemberRoleGetVO result = new MemberRoleGetVO();
        result.setId(memberRoleDO.getId());
        result.setRoleName(memberRoleDO.getRoleName());
        result.setRemark(memberRoleDO.getRemark());
        result.setStatus(memberRoleDO.getStatus());
        result.setImFlag(memberRoleDO.getHasImAuth());

        //全量权限从会员获得
        List<AuthTreeMenuVO> menuTree = AuthBOUtils.transferToTree(memberAuth.getAuth());
        result.setAuth(menuTree);

        //勾选的权限从角色本身获得
        List<Long> checkIds = memberRoleDO.getAuth().stream().map(AuthBO::getId).collect(Collectors.toList());
        result.setCheckIds(checkIds);

        return Wrapper.success(result);
    }


    /**
     * 查询会员角色左侧树形权限菜单中勾选的Id列表
     *
     * @param headers HttpHeaders信息
     * @param idVO    接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<AuthTreeMenuButtonCheckIdVO> getTreeCheckIds(HttpHeaders headers, MemberRoleIdVO idVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        MemberDO memberDO = memberRepository.findById(loginUser.getMemberId()).orElse(null);
        if (memberDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_DOES_NOT_EXIST);
        }

        AuthTreeMenuButtonCheckIdVO result = new AuthTreeMenuButtonCheckIdVO();
        List<Long> checkIds = new ArrayList<>();
        if (NumberUtil.isPositive(idVO.getMemberRoleId())) {
            MemberRoleDO memberRoleDO = memberRoleRepository.findFirstByMemberAndId(memberDO, idVO.getMemberRoleId());
            if (memberRoleDO == null) {
                return Wrapper.fail(ResponseCode.MC_MS_MEMBER_ROLE_DOES_NOT_EXIST);
            }

            if (!CollectionUtils.isEmpty(memberRoleDO.getAuth())) {
                checkIds = memberRoleDO.getAuth().stream().map(AuthBO::getId).collect(Collectors.toList());
            }
        }

        result.setCheckIds(checkIds);
        return Wrapper.success(result);
    }

    /**
     * 更新会员角色及左侧菜单权限
     *
     * @param headers  HttpHeaders信息
     * @param updateVO 接口参数
     * @return 操作结果
     */
    @Override
    @Transactional(rollbackFor = BusinessException.class)
    public Wrapper<Void> updateMemberRole(HttpHeaders headers, MemberAbilityRoleUpdateVO updateVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        MemberDO memberDO = memberRepository.findById(loginUser.getMemberId()).orElse(null);
        if (memberDO == null || memberDO.getMemberAuth() == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_DOES_NOT_EXIST);
        }

        MemberRoleDO memberRoleDO = memberRoleRepository.findById(updateVO.getMemberRoleId()).orElse(null);
        if (memberRoleDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_ROLE_DOES_NOT_EXIST);
        }

        if (memberRoleRepository.existsByMemberAndRoleNameAndIdNot(memberDO, updateVO.getRoleName(), memberRoleDO.getId())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_ROLE_EXISTS);
        }

        //不能更改会员“超级管理员”用户角色
        if (memberRoleDO.getTypeEnum().equals(MemberUserAuthTypeEnum.ADMIN.getCode())) {
            return Wrapper.fail(ResponseCode.MC_MS_FORBID_DELTE_OR_UPDATE_MEMBER_ROLE);
        }

        if(CollectionUtils.isEmpty(updateVO.getAuth())) {
            updateVO.setAuth(new ArrayList<>());
        }

        //复制
        List<AuthBO> memberAuthList = memberDO.getMemberAuth().getAuth();

        //参数校验，注意菜单权限可能为空
        List<Long> configMenuIds = CollectionUtils.isEmpty(updateVO.getAuth()) ? new ArrayList<>() : updateVO.getAuth().stream().filter(MemberAbilityDataAuthVO::getChecked).map(MemberAbilityDataAuthVO::getMenuId).collect(Collectors.toList());
        List<Long> menuIds = memberAuthList.stream().map(AuthBO::getId).collect(Collectors.toList());
        if (configMenuIds.stream().anyMatch(configMenuId -> !menuIds.contains(configMenuId))) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_AUTH_DOES_NOT_EXIST);
        }

        List<MenuDO> menuDOList = menuRepository.findByIdInAndSourceNot(configMenuIds, UserLoginSourceEnum.BUSINESS_MANAGEMENT_PLATFORM.getCode()).stream().sorted(Comparator.comparingLong(MenuDO::getId)).collect(Collectors.toList());
        if (configMenuIds.stream().anyMatch(configMenuId -> menuDOList.stream().noneMatch(menuDO -> menuDO.getId().equals(configMenuId)))) {
            return Wrapper.fail(ResponseCode.MC_MS_MENU_DOES_NOT_EXIST);
        }

        List<Long> dataAuthConfigMenuIds = menuDOList.stream().filter(menuDO -> menuDO.getDataAuthConfig() != null && menuDO.getDataAuthConfig().equals(EnableDisableStatus.ENABLE.getCode())).map(MenuDO::getId).collect(Collectors.toList());
        List<Long> configHasDataAuthConfigMenuIds = updateVO.getAuth().stream().filter(auth -> auth.getChecked() && NumberUtil.notNullOrZero(auth.getHasDataAuth()) && auth.getHasDataAuth().equals(EnableDisableStatus.ENABLE.getCode())).map(MemberAbilityDataAuthVO::getMenuId).collect(Collectors.toList());
        if(configHasDataAuthConfigMenuIds.stream().anyMatch(configId -> !dataAuthConfigMenuIds.contains(configId))) {
            return Wrapper.fail(ResponseCode.MC_MS_MENU_CAN_NOT_SET_DATA_AUTH);
        }

        //参数校验：关联的组织机构
        List<Long> configOrgIds = new ArrayList<>();
        if(!CollectionUtils.isEmpty(updateVO.getAuth())) {
            configOrgIds = updateVO.getAuth().stream().filter(auth -> auth.getChecked() && NumberUtil.notNullOrZero(auth.getHasDataAuth()) && auth.getHasDataAuth().equals(EnableDisableStatus.ENABLE.getCode()) && !CollectionUtils.isEmpty(auth.getOrgIds())).flatMap(auth -> auth.getOrgIds().stream()).distinct().collect(Collectors.toList());
        }

        List<Long> memberOrgIds = memberOrganizationRepository.findByMember(memberDO).stream().map(MemberOrganizationDO::getId).collect(Collectors.toList());
        if (configOrgIds.stream().anyMatch(configOrgId -> !memberOrgIds.contains(configOrgId))) {
            return Wrapper.fail(ResponseCode.MC_MS_ORGANIZATION_DOES_NOT_EXIST);
        }

        //修改：角色名称、说明，是否有IM权限
        memberRoleDO.setRoleName(updateVO.getRoleName());
        memberRoleDO.setRemark(StringUtils.hasLength(updateVO.getRemark()) ? updateVO.getRemark().trim() : "");
        memberRoleDO.setHasImAuth(updateVO.getImFlag() ? EnableDisableStatus.ENABLE.getCode() : EnableDisableStatus.DISABLE.getCode());

        //修改：菜单权限
        List<AuthBO> roleAuthList = AuthBOUtils.copyList(memberRoleDO.getAuth());

        //删除菜单
        roleAuthList.removeIf(roleAuth -> updateVO.getAuth().stream().filter(auth -> !auth.getChecked()).anyMatch(auth -> auth.getMenuId().equals(roleAuth.getId())));

        //新增菜单（这里一定要对会员权限列表做复制，否则JPA会修改会员权限）
        //先从会员权限中找到要新增的菜单、按钮
        List<AuthBO> addAuthList = AuthBOUtils.copyList(memberAuthList.stream().filter(memberAuth -> updateVO.getAuth().stream().filter(MemberAbilityDataAuthVO::getChecked).anyMatch(auth -> auth.getMenuId().equals(memberAuth.getId()))).collect(Collectors.toList()));
        addAuthList.forEach(auth -> updateVO.getAuth().stream().filter(a -> a.getChecked() && a.getMenuId().equals(auth.getId())).findFirst().ifPresent(a -> {
            if(CollectionUtils.isEmpty(a.getButtonIds())) {
                auth.setButtons(new ArrayList<>());
            } else {
                auth.getButtons().removeIf(button -> !a.getButtonIds().contains(button.getButtonId()));
            }
        }));

        //修改按钮
        roleAuthList.forEach(roleAuth -> addAuthList.stream().filter(addAuth -> addAuth.getId().equals(roleAuth.getId())).findFirst().ifPresent(addAuth -> roleAuth.setButtons(AuthBOUtils.copyButtonList(addAuth.getButtons()))));
        //roleAuthList.forEach(roleAuth -> addAuthList.stream().filter(addAuth -> addAuth.getId().equals(roleAuth.getId())).findFirst().ifPresent(addAuth -> roleAuth.getButtons().removeIf(button -> addAuth.getButtons().stream().noneMatch(b -> b.getButtonId().equals(button.getButtonId())))));

        //添加菜单
        roleAuthList.addAll(addAuthList.stream().filter(addAuth -> roleAuthList.stream().noneMatch(roleAuth -> roleAuth.getId().equals(addAuth.getId()))).collect(Collectors.toList()));
        memberRoleDO.setAuth(roleAuthList);

        //修改：数据权限配置
        List<MemberRoleAuthConfigDO> authConfigList = new ArrayList<>(memberRoleDO.getAuthConfig());

        //先删除
        List<Long> deleteMenuIds = updateVO.getAuth().stream().filter(auth -> !auth.getChecked() || NumberUtil.isNullOrZero(auth.getHasDataAuth())).map(MemberAbilityDataAuthVO::getMenuId).collect(Collectors.toList());
        List<MemberRoleAuthConfigDO> deleteList = authConfigList.stream().filter(authConfig -> deleteMenuIds.contains(authConfig.getMenu().getId())).collect(Collectors.toList());
        //移除
        authConfigList.removeIf(deleteList::contains);

        //删除关联中间表的数据
        deleteList.forEach(authConfig -> authConfig.getOrgs().clear());
        memberRoleAuthConfigRepository.deleteAll(deleteList);

        //构建要新增的数据
        List<MemberRoleAuthConfigDO> newAuthConfigList = updateVO.getAuth().stream().filter(auth -> auth.getChecked() && NumberUtil.notNullOrZero(auth.getHasDataAuth()) && auth.getHasDataAuth().equals(EnableDisableStatus.ENABLE.getCode())).map(auth -> {
            MemberRoleAuthConfigDO authConfigDO = new MemberRoleAuthConfigDO();
            authConfigDO.setMemberId(memberDO.getId());
            //关联的菜单
            authConfigDO.setMenu(menuDOList.stream().filter(menu -> menu.getId().equals(auth.getMenuId())).findFirst().orElse(null));

            //是否具有数据权限
            authConfigDO.setHasDataAuth(EnableDisableStatus.ENABLE.getCode());

            //数据权限关联的组织机构
            if(CollectionUtils.isEmpty(auth.getOrgIds())) {
                authConfigDO.setOrgs(new HashSet<>());
            } else {
                authConfigDO.setOrgs(memberDO.getOrgs().stream().filter(memberOrganizationDO -> auth.getOrgIds().contains(memberOrganizationDO.getId())).collect(Collectors.toSet()));
            }

            return authConfigDO;
        }).collect(Collectors.toList());

        //修改（组织机构）
        authConfigList.forEach(authConfig -> newAuthConfigList.stream().filter(newAuthConfig -> newAuthConfig.getMenu().getId().equals(authConfig.getMenu().getId())).findFirst().ifPresent(newAuthConfig -> authConfig.setOrgs(newAuthConfig.getOrgs())));

        //新增
        authConfigList.addAll(newAuthConfigList.stream().filter(newAuthConfig -> authConfigList.stream().noneMatch(authConfig -> authConfig.getMenu().getId().equals(newAuthConfig.getMenu().getId()))).collect(Collectors.toList()));

        memberRoleAuthConfigRepository.saveAll(authConfigList);
        memberRoleDO.setAuthConfig(new HashSet<>(authConfigList));

        memberRoleRepository.saveAndFlush(memberRoleDO);

        //通知工作流服务，关联流程
        workflowFeignService.upsertMemberRoleToProcessAsync(loginUser.getMemberId(), memberRoleDO.getId(), memberRoleDO.getRoleName(), memberRoleDO.getAuth());

        //更新用户权限
        Wrapper<?> result = baseAuthService.updateMemberUserAuthByUpdateMemberRole(memberRoleDO);
        if(result.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(result.getCode(), result.getMessage());
        }

        //重构用户数据权限
        return baseAuthService.rebuildMemberUserDataAuth(memberDO);
    }

    /**
     * 更新会员角色菜单关联按钮
     *
     * @param headers  HttpHeaders信息
     * @param upsertVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> updateMemberRoleButton(HttpHeaders headers, MemberRoleUpdateButtonVO upsertVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        MemberDO memberDO = memberRepository.findById(loginUser.getMemberId()).orElse(null);
        if (memberDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_DOES_NOT_EXIST);
        }

        MemberRoleDO memberRoleDO = memberRoleRepository.findFirstByMemberAndId(memberDO, upsertVO.getMemberRoleId());
        if (memberRoleDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_ROLE_DOES_NOT_EXIST);
        }

        //不能更改会员“超级管理员”角色
        if (memberRoleDO.getTypeEnum().equals(MemberUserAuthTypeEnum.ADMIN.getCode())) {
            return Wrapper.fail(ResponseCode.MC_MS_FORBID_DELTE_OR_UPDATE_MEMBER_ROLE);
        }

        AuthBO memberAuthBO = memberDO.getMemberAuth().getAuth().stream().filter(menu -> menu.getId().equals(upsertVO.getMenuId())).findFirst().orElse(null);
        if (memberAuthBO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_AUTH_DOES_NOT_EXIST);
        }

        AuthBO authBO = memberRoleDO.getAuth().stream().filter(menu -> menu.getId().equals(upsertVO.getMenuId())).findFirst().orElse(null);
        if (authBO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_ROLE_MENU_DOES_NOT_EXIST);
        }

        //检验按钮是否存在
        if (CollectionUtils.isEmpty(memberAuthBO.getButtons())) {
            if (!CollectionUtils.isEmpty(upsertVO.getButtonIds())) {
                return Wrapper.fail(ResponseCode.MC_MS_MEMBER_ROLE_BUTTON_DOES_NOT_EXIST);
            }
        } else {
            if (!CollectionUtils.isEmpty(upsertVO.getButtonIds())) {
                if (!upsertVO.getButtonIds().stream().allMatch(buttonId -> memberAuthBO.getButtons().stream().anyMatch(button -> button.getButtonId().equals(buttonId)))) {
                    return Wrapper.fail(ResponseCode.MC_MS_MEMBER_ROLE_BUTTON_DOES_NOT_EXIST);
                }
            }
        }

        if (CollectionUtils.isEmpty(upsertVO.getButtonIds())) {
            authBO.getButtons().clear();
        } else {
            //移除不存在的
            authBO.getButtons().removeIf(button -> !upsertVO.getButtonIds().contains(button.getButtonId()));
            //新增
            List<Long> addButtonIds = upsertVO.getButtonIds().stream().filter(b -> authBO.getButtons().stream().noneMatch(button -> button.getButtonId().equals(b))).collect(Collectors.toList());
            List<ButtonBO> buttons = memberAuthBO.getButtons().stream().filter(button -> addButtonIds.contains(button.getButtonId())).collect(Collectors.toList());
            authBO.getButtons().addAll(buttons);
        }

        memberRoleRepository.saveAndFlush(memberRoleDO);

        Wrapper<?> result = baseAuthService.updateMemberUserAuthByUpdateMemberRole(memberRoleDO);
        if(result.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(result.getCode(), result.getMessage());
        }

        return Wrapper.success();
    }

    /**
     * 删除会员角色
     *
     * @param headers HttpHeaders信息
     * @param idVO    接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> deleteMemberRole(HttpHeaders headers, MemberRoleIdVO idVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        MemberDO memberDO = memberRepository.findById(loginUser.getMemberId()).orElse(null);
        if (memberDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_DOES_NOT_EXIST);
        }

        MemberRoleDO memberRoleDO = memberRoleRepository.findFirstByMemberAndId(memberDO, idVO.getMemberRoleId());
        if (memberRoleDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_ROLE_DOES_NOT_EXIST);
        }

        //不能更改会员“超级管理员”用户
        if (memberRoleDO.getTypeEnum().equals(MemberUserAuthTypeEnum.ADMIN.getCode())) {
            return Wrapper.fail(ResponseCode.MC_MS_FORBID_DELTE_OR_UPDATE_MEMBER_ROLE);
        }

        //如果已经有用户，不能删除
        if (!CollectionUtils.isEmpty(memberRoleDO.getUsers())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_ROLE_CANNOT_DELETE_WHEN_USER_EXISTS);
        }

        List<MemberRoleAuthConfigDO> authConfigDOList = new ArrayList<>(memberRoleDO.getAuthConfig());
        if(!CollectionUtils.isEmpty(authConfigDOList)) {
            authConfigDOList.forEach(authConfig -> authConfig.getOrgs().clear());

            memberRoleAuthConfigRepository.deleteAll(memberRoleDO.getAuthConfig());
        }

        memberRoleRepository.delete(memberRoleDO);

        //通知工作流服务，移除会员自定义角色的关联
        workflowFeignService.removeMemberRoleInProcessAsync(loginUser.getMemberId(), idVO.getMemberRoleId());

        return Wrapper.success();
    }

    /**
     * 更新会员角色状态
     *
     * @param headers  HttpHeaders信息
     * @param statusVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> updateMemberRoleStatus(HttpHeaders headers, MemberRoleUpdateStatusVO statusVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        MemberDO memberDO = memberRepository.findById(loginUser.getMemberId()).orElse(null);
        if (memberDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_DOES_NOT_EXIST);
        }

        MemberRoleDO memberRoleDO = memberRoleRepository.findFirstByMemberAndId(memberDO, statusVO.getId());
        if (memberRoleDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_ROLE_DOES_NOT_EXIST);
        }

        //不能更改会员“超级管理员”用户
        if (memberRoleDO.getTypeEnum().equals(MemberUserAuthTypeEnum.ADMIN.getCode())) {
            return Wrapper.fail(ResponseCode.MC_MS_FORBID_DELTE_OR_UPDATE_MEMBER_ROLE);
        }

        //如果已经有用户，不能修改状态
        if (!CollectionUtils.isEmpty(memberRoleDO.getUsers())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_ROLE_CANNOT_DELETE_WHEN_USER_EXISTS);
        }

        memberRoleDO.setStatus(statusVO.getStatus());
        memberRoleRepository.saveAndFlush(memberRoleDO);

        if (memberRoleDO.getStatus().equals(EnableDisableStatus.ENABLE.getCode())) {
            workflowFeignService.upsertMemberRoleToProcessAsync(loginUser.getMemberId(), memberRoleDO.getId(), memberRoleDO.getRoleName(), memberRoleDO.getAuth());
        } else {
            workflowFeignService.removeMemberRoleInProcessAsync(loginUser.getMemberId(), memberRoleDO.getId());
        }

        return Wrapper.success();
    }
}
